package com.xzan.medusaweb.test.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class EchoClient {
    public void start() {
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class)
                .option(ChannelOption.SO_KEEPALIVE, Boolean.TRUE)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                ByteBuf byteBuf = (ByteBuf) msg;
                                byte[] bytes = new byte[byteBuf.readableBytes()];
                                String data = new String(bytes, "utf-8");
                                System.out.println("from server:" + data);
                                ctx.close();
                            }
                        });
                    }
                });
        try {
            while (Boolean.TRUE) {
                ChannelFuture future = bootstrap.connect("localhost", 8080).sync();
                future.channel().writeAndFlush(Unpooled.copiedBuffer("Hello netty".getBytes()));
                Thread.sleep(4000);
                future.channel().closeFuture().sync();
            }
        } catch (Exception e) {

        }
    }

    public static void main(String[] args) {
        EchoClient client = new EchoClient();
        client.start();
    }
}
